package com.example.denglu;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    // 定义消息代码
    private static final int LOGIN_START = 1;
    private static final int LOGIN_FINISH = 2;
    private static final int LOGIN_SUCCESS = 3;
    private static final int LOGIN_FAILED = 4;

    private EditText editTextUsername;
    private EditText editTextPassword;
    private Button buttonLogin;
    private Button buttonRegister;
    private ProgressBar progressBar;
    private TextView textViewLoading;
    private View viewLoadingMask;

    // 声明线程变量，用于在Activity销毁时中断
    private Thread loginThread;
    private String username; // 保存用户名用于传递

    // 消息处理器
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_START:
                    showLoading();
                    break;
                case LOGIN_FINISH:
                    hideLoading();
                    break;
                case LOGIN_SUCCESS:
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                    // 跳转到HomeActivity并传递用户名
                    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                    intent.putExtra("username", username);
                    startActivity(intent);
                    // 关闭当前页面，防止返回
                    finish();
                    break;
                case LOGIN_FAILED:
                    Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化控件
        initViews();

        // 设置按钮点击事件
        setButtonListeners();
    }

    // 初始化所有视图控件
    private void initViews() {
        editTextUsername = findViewById(R.id.editText_username);
        editTextPassword = findViewById(R.id.editText_password);
        buttonLogin = findViewById(R.id.button_login);
        buttonRegister = findViewById(R.id.button_register);
        progressBar = findViewById(R.id.progressBar);
        textViewLoading = findViewById(R.id.textView_loading);
        viewLoadingMask = findViewById(R.id.view_loading_mask);
    }

    // 设置按钮点击监听器
    private void setButtonListeners() {
        buttonLogin.setOnClickListener(v -> handleLogin());
        buttonRegister.setOnClickListener(v -> {
            // 实际应用中应实现注册逻辑
            Toast.makeText(MainActivity.this, "注册功能待实现", Toast.LENGTH_SHORT).show();
        });
    }

    // 处理登录逻辑
    private void handleLogin() {
        // 获取用户输入的用户名和密码
        username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();

        // 输入验证
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // 启动新线程执行耗时操作
        loginThread = new Thread(() -> {
            // 发送开始登录的消息
            handler.sendEmptyMessage(LOGIN_START);

            try {
                // 模拟网络请求，休眠2秒
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // 线程被中断时结束
                return;
            }

            // 发送结束登录的消息（隐藏进度条）
            handler.sendEmptyMessage(LOGIN_FINISH);

            // 验证用户名和密码（假设test/123456为有效账号）
            if ("test".equals(username) && "123456".equals(password)) {
                handler.sendEmptyMessage(LOGIN_SUCCESS);
            } else {
                handler.sendEmptyMessage(LOGIN_FAILED);
            }
        });

        loginThread.start();
    }

    // 显示加载状态
    private void showLoading() {
        progressBar.setVisibility(View.VISIBLE);
        textViewLoading.setVisibility(View.VISIBLE);
        viewLoadingMask.setVisibility(View.VISIBLE);
        buttonLogin.setEnabled(false);
        buttonRegister.setEnabled(false);
    }

    // 隐藏加载状态
    private void hideLoading() {
        progressBar.setVisibility(View.GONE);
        textViewLoading.setVisibility(View.GONE);
        viewLoadingMask.setVisibility(View.GONE);
        buttonLogin.setEnabled(true);
        buttonRegister.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 移除所有未处理的消息，防止内存泄漏
        handler.removeCallbacksAndMessages(null);

        // 中断可能仍在运行的登录线程
        if (loginThread != null && loginThread.isAlive()) {
            loginThread.interrupt();
        }
    }
}
